package cn.zl.ymcc.exception;

import cn.zl.ymcc.exception.errorCode.ErrorCode;
import cn.zl.ymcc.result.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(GlobalBusinessException.class)
    public Result handleException(GlobalBusinessException e){
        e.printStackTrace();
        return Result.error(e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        e.printStackTrace();
        return Result.error(ErrorCode.NETWORK_ERROR);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleException(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<String> errorMessage = e.getBindingResult().getAllErrors().stream().map(
                objectError -> objectError.getDefaultMessage()
        ).collect(Collectors.toList());
        System.err.println(errorMessage);
        return Result.error(errorMessage);
    }
}
